<template>
  <div class="pokemon-home">
    <h1 style="text-align: center; margin-bottom: 30px;">宝可梦图鉴</h1>

    <!-- 搜索框 -->
    <div style="text-align: center; margin-bottom: 30px;">
      <el-input
        v-model="searchText"
        placeholder="搜索宝可梦..."
        style="width: 300px;"
        clearable
        @input="handleSearch"
      />
    </div>

    <!-- 宝可梦列表 -->
    <el-row :gutter="20">
      <el-col
        v-for="pokemon in displayPokemons"
        :key="pokemon.id"
        :span="4"
        style="margin-bottom: 20px;"
      >
        <el-card
          style="cursor: pointer; text-align: center;"
          @click="goToDetail(pokemon.id)"
          shadow="hover"
        >
          <div style="height: 100px; display: flex; align-items: center; justify-content: center;">
            <img
              :src="pokemon.image"
              :alt="pokemon.name"
              style="max-width: 80px; max-height: 80px;"
            />
          </div>
          <div style="margin-top: 10px;">
            <div style="font-size: 12px; color: #999;">
              #{{ pokemon.id.toString().padStart(3, '0') }}
            </div>
            <div style="font-weight: bold; margin-top: 5px;">
              {{ pokemon.name }}
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 加载状态 -->
    <div v-if="loading" style="text-align: center; padding: 50px;">
      <el-skeleton :rows="5" animated />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

// 数据状态
const allPokemons = ref<any[]>([])
const loading = ref(false)
const searchText = ref('')
const router = useRouter()

// 计算显示的宝可梦列表（支持搜索）
const displayPokemons = computed(() => {
  if (!searchText.value) return allPokemons.value
  return allPokemons.value.filter(pokemon =>
    pokemon.name.toLowerCase().includes(searchText.value.toLowerCase())
  )
})

// 获取宝可梦列表
const loadPokemons = async () => {
  try {
    loading.value = true
    const response = await axios.get('https://pokeapi.co/api/v2/pokemon', {
      params: { limit: 151, offset: 0 }
    })

    allPokemons.value = response.data.results.map((pokemon: any, index: number) => ({
      id: index + 1,
      name: pokemon.name,
      image: `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${index + 1}.png`
    }))
  } catch (error) {
    console.error('加载宝可梦失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  // 搜索逻辑已经在 computed 中处理了
  console.log('搜索:', searchText.value)
}

// 跳转到详情页
const goToDetail = (id: number) => {
  router.push(`/pokemon/${id}`)
}

// 组件加载时获取数据
onMounted(() => {
  loadPokemons()
})
</script>
